package com.alcj.common.utils;

import com.alcj.common.vcode.Captcha;
import com.alcj.common.vcode.GifCaptcha;
import com.alcj.common.vcode.JpgCaptcha;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.context.request.WebRequest;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Arrays;
import java.util.Map;
import java.util.Random;
import java.util.UUID;

/**
 * @author : chenxh
 * @version :v1.0
 * @Package : com.alcj.common.utils
 * @Description :(生成验证码)
 * @date : 2017/10/13 9:38
 */
public class VerifyCodeUtil {

    private static final Logger logger = LoggerFactory.getLogger(VerifyCodeUtil.class);
    //jpg扩展名
    public static final String EXTENSION_JPG = ".jpg";

    //gif扩展名
    public static final String EXTENSION_GIF = ".gif";

    //验证码访问地址
    public static final String IMG_UPLOAD_PATH = "../upload/vcode/";

    /**
     * 生成静态验证码
     *
     * @param uploadPath 存储路径
     * @return 验证码图片名称
     */
    public static String CreateJpgCode(String uploadPath, HttpSession session) throws Exception {

        // 生成静态验证码
        String imgName = UUID.randomUUID().toString().replaceAll("-", "") + EXTENSION_JPG;
        String verifyCode = JpgCaptcha.generateVerifyCode(4);
        JpgCaptcha.outputImage(146, 33, new FileOutputStream(uploadPath + imgName), verifyCode);
        session.setAttribute("verifyCode", verifyCode.toLowerCase());
        return IMG_UPLOAD_PATH + imgName;
    }

    /**
     * 生成动态验证码
     *
     * @param uploadPath 存储路径
     * @return 验证码图片名称
     */
    public static String CreateGifCode(String uploadPath, HttpSession session) throws Exception {

        // 生成动态验证码
        Captcha captcha = new GifCaptcha(146, 33, 4);
        //输出
        String imgName = UUID.randomUUID().toString().replaceAll("-", "") + EXTENSION_GIF;
        captcha.out(new FileOutputStream(uploadPath + imgName));
        session.setAttribute("verifyCode", captcha.text().toLowerCase());
        return IMG_UPLOAD_PATH + imgName;
    }

    /**
     * 生成手机验证码
     *
     * @param :发送手机号
     * @param :会话
     * @return
     */
    public static String CreatePhoneCode(String phone) {
        try {
            String str_userid = "13491";
            String str_account = "SportApp";
            String str_password = "123456";
            String verifyCode = JpgCaptcha.generateVerifyCode(6, "0123456789");
            String str_content = "【安联车检】验证码：" + verifyCode + "，您正进行安联车检的身份认证，打死不要告诉别人！";
            String str_mobile = phone;//130xxxxxxxx,131xxxxxxxx多个号码用英文半角‘,’分隔
            URL url = new URL("http://www.duanxin10086.com/sms.aspx");
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setRequestMethod("POST");
            connection.setUseCaches(false);
            connection.setInstanceFollowRedirects(true);
            connection.setRequestProperty("Charset", "UTF-8");
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

            connection.connect();

            OutputStream out = connection.getOutputStream();
            JSONObject jsonObj = new JSONObject();
            String param = "action=send&userid=" + str_userid + "&account=" + str_account + "&password=" + str_password + "&content=" + str_content + "&mobile=" + str_mobile;
            jsonObj.put("action", "send");
            jsonObj.put("userid", str_userid);
            jsonObj.put("account", str_account);
            jsonObj.put("password", str_password);
            jsonObj.put("content", str_content);
            jsonObj.put("mobile", str_mobile);

            out.write(param.toString().getBytes("UTF-8"));
            out.flush();
            out.close();

            // 读取响应
            XmlMsgParseUtil xmlmsg = new XmlMsgParseUtil();
            Map<String,String> resultData =  xmlmsg.getTextMsg(connection.getInputStream());

            // 断开连接
            connection.disconnect();
            // 返回发送结果
            logger.info(resultData.toString());
            // 发送失败
            if(resultData.get("returnstatus").equals("Faild")){
                verifyCode = "";
            }

            return verifyCode;
        } catch (Exception e) {
            // 异常报错
            logger.error("获取手机验证码异常 : {}", e.getMessage());
            logger.error("异常详细信息 :", e);
            return "";
        }
    }
    /**
     * 输出指定验证码图片流
     * @param os
     * @param code
     * @throws IOException
     */
    public static void outputImage(OutputStream os, String code) throws IOException{
        int w = 146;
        int h = 33;
        // 生成图片
        JpgCaptcha.outputImage(146,33,os,code);
    }
}
